package com.crm.system.controller.permissionManagement;

import com.alibaba.fastjson.JSON;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysAccountPermission;
import com.crm.model.entity.sys.permissionManagement.SysPermissionGroup;
import com.crm.model.vo.permissionManagement.SysPermissionGroupVO;
import com.crm.service.sys.permissionManagement.SysMenuDbService;
import com.crm.system.service.permissionManagement.SysAccountPermissionService;
import com.crm.system.service.permissionManagement.SysMenuService;
import com.crm.system.service.permissionManagement.SysPermissionGroupService;
import com.crm.system.service.permissionManagement.SysPermissionManagementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author wangfei
 * @date 2020/12/07 14:06
 */
@Controller
@RequestMapping("/permissionManagement")
@Slf4j
public class PermissionManagementController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    SysPermissionManagementService sysPermissionManagementService;

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    SysMenuDbService sysMenuDbService;

    @Autowired
    SysAccountPermissionService sysAccountPermissionService;

    @Autowired
    SysPermissionGroupService sysPermissionGroupService;

    /**
     * 获取权限组名单列表接口
     * @author wll
     * @param pageIndex
     * @param pageSize
     * @param searchInfo 搜索条件
     * @return
     */
    @PostMapping("/getPermissionManagementList")
    @ResponseBody
    public DataResponse getPermissionManagementList(@RequestParam(value = "pageIndex") Integer pageIndex,
                                @RequestParam(value = "pageSize") Integer pageSize,
                                @RequestParam(value = "permissionGroupName", required = false) String searchInfo) {
        try{
            DhPageInfo<SysPermissionGroupVO> permissionManagement = sysPermissionManagementService.getPermissionManagementList(pageIndex, pageSize, searchInfo);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), permissionManagement);
        }catch(Exception e){
            log.error("permissionManagement getPermissionManagementList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }

    }

    /**
     * 保存账号-权限组关联表
     * @param request
     * @param permissionGroupId
     * @param accountIds
     * @return
     */
    @PostMapping("/saveAccountPermission")
    @ResponseBody
    public DataResponse saveAccountPermission(HttpServletRequest request,
                                @RequestParam(value = "permissionGroupId", required = false) String permissionGroupId,
                                @RequestParam(value = "accountIds", required = false) String accountIds) {
        try{
            if(!StringUtils.isBlank(permissionGroupId)){
                sysAccountPermissionService.addSysAccountPermission(permissionGroupId,accountIds);
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("permissionManagement saveAccountPermission error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 添加权限组
     * @param createPermissionGroupJson
     * @return
     */
    @PostMapping("/addPermissionGroup")
    @ResponseBody
    public DataResponse addPermissionGroup(@RequestParam String createPermissionGroupJson,
                                           @RequestParam(value="permissionGroupId", required=false) String permissionGroupId){
        try{
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            sysPermissionManagementService.insertSysPermissionGroup(createPermissionGroupJson,userAccount.getAccountId(),permissionGroupId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }catch(Exception e){
            log.error("permissionManagement addPermissionGroup error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 删除权限组
     * @param request
     * @param permissionGroupId
     * @return
     */
    @PostMapping("/delPermissionGroup")
    @ResponseBody
    public DataResponse delPermissionGroup(HttpServletRequest request,
                                @RequestParam(value = "permissionGroupId", required = false) String permissionGroupId) {
        try{
            if(!StringUtils.isBlank(permissionGroupId)){
                sysPermissionManagementService.delPermissionGroup(permissionGroupId);
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("permissionManagement delPermissionGroup error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 是否有权限
     * @param request
     * @param permissionGroupId
     * @return
     */
    @PostMapping("/whetherHavePermission")
    @ResponseBody
    public DataResponse whetherHavePermission(HttpServletRequest request,
                                           @RequestParam(value = "permissionGroupId", required = false) String permissionGroupId) {
        try{
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            if(!StringUtils.isBlank(permissionGroupId) && userAccount != null){
                boolean admin = CommonUtils.isAdmin(userAccount.getUserId());
                List<SysAccountPermission> sysAccountPermissionList
                        = sysAccountPermissionService.selectSysAccountPermissionList(permissionGroupId, userAccount.getAccountId());
                if((sysAccountPermissionList != null && !sysAccountPermissionList.isEmpty()) || admin){
                    return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), true);
                }
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode(), false);
        }catch(Exception e){
            log.error("permissionManagement whetherHavePermission error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode(), false);
        }
    }

    /**
     * 获取权限组功能树
     * @param request
     * @return
     */
    @PostMapping("/getPermissionTree")
    @ResponseBody
    public DataResponse getPermissionTree(HttpServletRequest request, ModelMap model,
                                          @RequestParam(value="permissionGroupId", required=false) String permissionGroupId){
        try {
            Map<String, List<Map<String, Object>>> permissionTree = sysMenuService.getPermissionTree(permissionGroupId);
            if(permissionTree != null){
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), JSON.toJSON(permissionTree));
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("permissionManagement getPermissionTree error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 权限组名单-权限组详情跳转
     * @return
     */
    @GetMapping("/permissionGroupDetail")
    public String permissionGroupDetail(HttpServletRequest request, ModelMap model,
                                        @RequestParam(value="permissionGroupId") String permissionGroupId){
        String permissionGroupName = "";
        String remark = "";
        model.addAttribute("permissionGroupId",permissionGroupId);
        SysPermissionGroup sysPermissionGroup = sysPermissionGroupService.selectSysPermissionGroupById(permissionGroupId);
        if(sysPermissionGroup != null){
            permissionGroupName = sysPermissionGroup.getPermissionGroupName();
            remark = sysPermissionGroup.getRemark();
        }
        model.addAttribute("permissionGroupName",permissionGroupName);
        model.addAttribute("remark",remark);
        return "crmSystem/permissionManager/permissionGroupDetail";
    }


}
